package com.db.utils;


import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

public class FileUtils {

    public static byte[] read(String filePath) {
        try {
            FileInputStream fileInputStream = new FileInputStream(filePath);
            int len = fileInputStream.available();
            byte[] bs = new byte[len];
            fileInputStream.read(bs);
            return bs;
        } catch (FileNotFoundException e) {
//            e.printStackTrace();
            System.out.println(filePath + " not exist");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * java 路径分隔符File.separator 以及 路径两种写法"/"和"\\"
     *
     * @return "/"和"\\"
     */
    public static String separator() {
        return File.separator;

    }

    /**
     * 创建目录(如果目录不存在就创建)
     *
     * @param destDirName
     * @return
     */
    public static boolean createDir(String destDirName) {
        File dir = new File(destDirName);
        if (dir.exists()) {
//	            System.out.println("创建目录" + destDirName + "失败，目标目录已经存在");  
            return false;
        }
        if (!destDirName.endsWith(File.separator)) {
            destDirName = destDirName + File.separator;
        }
        //创建目录
        if (dir.mkdirs()) {
            LogUtil.log("create dir" + destDirName + " success！");
            return true;
        } else {
            LogUtil.log("create dir " + destDirName + " failed！");
            return false;
        }
    }


    /**
     * 创建文件(如果文件不存在就创建)
     *
     * @param destDirName
     * @return 返回true表示文件成功  false 表示文件已经存在
     */
    public static boolean createNewFile(String destDirName) {
        String fileName = destDirName;

        File file = new File(fileName);

        try {
            if (file.createNewFile()) {
                System.out.println(destDirName + " created.");
            } else {
//			   System.out.println(destDirName+"文件已经存在不需要重复创建");
            }
            return true;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }


    /**
     * 删除单个文件
     *
     * @param sPath 被删除文件的文件名
     * @return 单个文件删除成功返回true，否则返回false
     */
    public static boolean deleteFile(String sPath) {
        boolean flag = false;
        File file = new File(sPath);
        // 路径为文件且不为空则进行删除
        if (file.isFile() && file.exists()) {
            file.delete();
            flag = true;
        }
        return flag;
    }

    /**
     * 删除目录（文件夹）以及目录下的文件
     *
     * @param sPath 被删除目录的文件路径
     * @return 目录删除成功返回true，否则返回false
     */
    public static boolean deleteDirectory(String sPath) {
        //如果sPath不以文件分隔符结尾，自动添加文件分隔符
        if (!sPath.endsWith(File.separator)) {
            sPath = sPath + File.separator;
        }
        File dirFile = new File(sPath);
        //如果dir对应的文件不存在，或者不是一个目录，则退出
        if (!dirFile.exists() || !dirFile.isDirectory()) {
            return false;
        }
        boolean flag = true;
        //删除文件夹下的所有文件(包括子目录)
        File[] files = dirFile.listFiles();
        for (int i = 0; i < files.length; i++) {
            //删除子文件
            if (files[i].isFile()) {
                flag = deleteFile(files[i].getAbsolutePath());
                if (!flag) break;
            } //删除子目录
            else {
                flag = deleteDirectory(files[i].getAbsolutePath());
                if (!flag) break;
            }
        }
        if (!flag) return false;
        //删除当前目录
        if (dirFile.delete()) {
            return true;
        } else {
            return false;
        }
    }


    /**
     * @Description：获取某个目录下所有直接下级文件，不包括目录下的子目录的下的文件，所以不用递归获取
     */
    public static List<String> getFiles(String path) {
        List<String> files = new ArrayList<String>();
        File file = new File(path);
        File[] tempList = file.listFiles();

        for (int i = 0; i < tempList.length; i++) {
            if (tempList[i].isFile()) {
//	                files.add(tempList[i].toString());
                files.add(tempList[i].getName());
                //文件名，不包含路径
                //String fileName = tempList[i].getName();
            }
            if (tempList[i].isDirectory()) {
                //这里就不递归了，
            }
        }
        return files;
    }


    /**
     * 读取文件每行数据如果包含strName 就返回内容
     * <string name="routing_info">CAUIAg</string> 读取行包含routing_info 返回内容CAUIAg
     *
     * @param strFile
     * @param strName return str
     */
    public static String readFileByLineContent(String strFile, String strName) {
        try {
            int count = readFileByLinelineCount(strFile);
//	        	 byte[] byteArray = new byte[count]   ;
            File file = new File(strFile);
            BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
            String strLine = null;
//	            int lineCount = 1;
//	            int i =0;
            while (null != (strLine = bufferedReader.readLine())) {
                //System.out.println( "第[" + lineCount + "]行数据:[" + strLine + "]");
//	            	System.out.println(   strLine  );

                if (strLine.contains(strName)) {
                    String str = "\">";
                    String contentStr = strLine.substring((strLine.indexOf(str) + 2), strLine.indexOf("</"));
                    return contentStr;
                }


//	            	String str = strLine.substring((strLine.indexOf("=")+1)).trim();

//	            	  byteArray[i] = (byte) Integer.parseInt( str) ;
//	                lineCount++;
//	                i++;
            }
//	            String str = new String(byteArray);
//	    		System.out.println("byteArray.toString()="+str);


        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 按行读取文件
     *
     * @param strFile
     */
    public static void readFileByLine(String strFile) {
        try {
            int count = readFileByLinelineCount(strFile);
            byte[] byteArray = new byte[count];
            File file = new File(strFile);
            BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
            String strLine = null;
            int lineCount = 1;
            int i = 0;
            while (null != (strLine = bufferedReader.readLine())) {
                //System.out.println( "第[" + lineCount + "]行数据:[" + strLine + "]");
//	            	System.out.println(   strLine  );
                String str = strLine.substring((strLine.indexOf("=") + 1)).trim();

                byteArray[i] = (byte) Integer.parseInt(str);
                lineCount++;
                i++;
            }
            String str = new String(byteArray);
            System.out.println("byteArray.toString()=" + str);


        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 读取文件第一行内容
     *
     * @param strFile
     */
    public static String readFileOneLine(String strFile) {
        try {
            int count = readFileByLinelineCount(strFile);
            if (count != 1) {
                return null;
            }
            File file = new File(strFile);
            BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
            String strLine = null;
//	            int lineCount = 1;
//	            int i =0;
            while (null != (strLine = bufferedReader.readLine())) {
                //System.out.println( "第[" + lineCount + "]行数据:[" + strLine + "]");
                System.out.println(strLine);
//	            	String str = strLine.substring((strLine.indexOf("=")+1)).trim();

//	            	  byteArray[i] = (byte) Integer.parseInt( str) ;
//	                lineCount++;
                return strLine;
//	                i++;
            }
//	            String str = new String(byteArray);
//	    		System.out.println("byteArray.toString()="+str);


        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 按行读取文件行数 返回总行数
     *
     * @param strFile
     */
    public static int readFileByLinelineCount(String strFile) {
        try {
            File file = new File(strFile);
            BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
            String strLine = null;
            int lineCount = 0;
            while (null != (strLine = bufferedReader.readLine())) {
                // logger.info("第[" + lineCount + "]行数据:[" + strLine + "]");
                lineCount++;
            }
            return lineCount;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }


    /**
     * 把byte[]数组写入文件中
     *
     * @param txtPath
     * @param byteArray
     */
    public static void writer(String txtPath, byte[] byteArray) {
        try {
            byte[] bArray = byteArray;//Data.byteArray();
            int blen = bArray.length;
            File file = new File(txtPath);  //存放数组数据的文件
            FileWriter out = new FileWriter(file);  //文件写入流
            //将数组中的数据写入到文件中。每行各数据之间TAB间隔
            for (int j = 0; j < blen; j++) {
                String str = j + " = " + bArray[j] + "";
                out.write(str);
                if (j < (blen - 1))
                    out.write("\r\n");
            }

            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static void writer(String filePath, String content) {
        File file = new File(filePath);
        writeFile(file, content, false);
    }

    public static boolean writeFile(String filePath, String content, boolean append) {
        File file = new File(filePath);
        return writeFile(file, content, append);
    }

    public static boolean writeFile(File file, String content, boolean append) {
        if (content == null) {
            return false;
        }

        FileWriter fileWriter = null;
        try {

            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            if (!file.exists()) {
                file.createNewFile();
            }
            fileWriter = new FileWriter(file, append);
            fileWriter.write(content);
            fileWriter.close();
            return true;

        } catch (IOException e) {
            throw new RuntimeException("IOException occurred. ", e);
        } finally {
            if (fileWriter != null) {
                try {
                    fileWriter.close();
                } catch (IOException e) {
                    throw new RuntimeException("IOException occurred. ", e);
                }
            }
        }
    }


    /**
     * 清空文件内容
     *
     * @param fileName
     */
    public static void clearInfoForFile(String fileName) {
        File file = new File(fileName);
        try {
            if (!file.exists()) {
                file.createNewFile();
            }
            FileWriter fileWriter = new FileWriter(file);
            fileWriter.write("");
            fileWriter.flush();
            fileWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 读取文本文件内容
     *
     * @param fileName 文件路径
     * @return
     */
    public static String readFileContent(String fileName) {
        File file = new File(fileName);
        return readFileContent(file);
//	        BufferedReader reader = null;
//	        StringBuffer sbf = new StringBuffer();
//	        try {
//	            reader = new BufferedReader(new FileReader(file));
//	            String tempStr;
//	            while ((tempStr = reader.readLine()) != null) {
//	                sbf.append(tempStr);
//	            }
//	            reader.close();
//	            return sbf.toString();
//	        } catch (IOException e) {
//	            e.printStackTrace();
//	        } finally {
//	            if (reader != null) {
//	                try {
//	                    reader.close();
//	                } catch (IOException e1) {
//	                    e1.printStackTrace();
//	                }
//	            }
//	        }
//	        return sbf.toString();
    }


    public static String readFileContent(File file) {
        BufferedReader reader = null;
        StringBuffer sbf = new StringBuffer();
        try {
            reader = new BufferedReader(new FileReader(file));
            String tempStr;
            while ((tempStr = reader.readLine()) != null) {
                sbf.append(tempStr);
            }
            reader.close();
            return sbf.toString();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
        return sbf.toString();
    }


    public static String getProperty(String path, String key, String defaultValue) {
        String value = defaultValue;
        try {
            if (!new File(path).exists()) {
                return value;
            }
            InputStream input = new FileInputStream(path);
            Properties prop = new Properties();
            prop.load(input);
            value = prop.getProperty(key) == null ? value : prop.getProperty(key);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return value;
    }

    public static String getProperty(String path, String key) {
        String value = "";
        try {
            if (!ensureExist(path)) {
                return "";
            }
            InputStream input = new FileInputStream(path);
            Properties prop = new Properties();

            prop.load(input);

            value = prop.getProperty(key) == null ? "" : prop.getProperty(key);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return value;
    }

    public static boolean writeProperty(String path, String key, String value) {
        boolean result = false;
        try {

            if (!ensureExist(path)) {
                return false;
            }


            InputStream input = new FileInputStream(path);
            Properties prop = new Properties();
            prop.load(input);


            if (prop.containsKey(key)) {
                prop.replace(key, value);
                System.out.print("exist!!!!");
            } else {
                prop.setProperty(key, value);
//				prop.put(key, value);
            }
            // save properties to project root folder
            OutputStream output = new FileOutputStream(path);
            prop.store(output, null);

            System.out.println(prop);

            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }


    public static boolean ensureExist(String filePath) {
        boolean result = false;
        try {
            File f = new File(filePath);
            if (f.exists()) {
                result = true;
            } else {
                if (!f.getParentFile().exists()) {
                    f.getParentFile().mkdirs();
                }
                result = f.createNewFile();// 不存在则创建
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;

    }

    public static boolean isExist(String filePath) {
        boolean result = false;
        File f = new File(filePath);
        if (f.exists()) {
            return true;
        } else {
            return false;
        }
    }

    public static boolean appendFileLine(String filePath, String content) {
        return writeFile(filePath, content.concat("\n"), true);
    }

    public static void writeBytes(String filePath, byte[] contents) {
        File file = new File(filePath);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        FileOutputStream fileOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream(file);
            fileOutputStream.write(contents);
            fileOutputStream.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fileOutputStream != null) {
                    fileOutputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static File getConfigFile() {
        // 把配置文件固定保存在工程运行目录下
        File file = new File(System.getProperty("user.dir"), "cfg.properties");
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return file;
    }

}
